<?php	namespace Admin\Controller;
class GoodsListController extends CommonController
{
	protected $db;
	protected $typeattr;
	protected $goodsAttr;
	public function __construct()
	{
		parent::__construct();
		$this->db = new \Admin\Model\GoodsList;//实例化货品列表
		$this->typeattr = new \Admin\Model\TypeAttr;//实力恶化类型属性表
		$this->goodsAttr = new \Admin\Model\GoodsAttr;//实例化商品属性表
	}
	
	/**
	 * 首页
	 */
	public function index()
	{	//get参数商品id和类型id
		$gid = Q('get.gid',0,'intaval');
		$type_ID = Q('get.type_ID',0,'intaval');
		if(IS_POST){
			if(!$this->db->store($gid)){
				$this->error($this->db->getError());	
			}
			View::success('添加成功');	
		}
		//获取规格数据
		$spec = $this->typeattr->where('type_ID',$type_ID)->where('taclass',1)->get();
		//获取商品属性表中商品添加的时候添加的规格
		foreach ($spec as $k => $v) {
			$spec[$k]['select'] = $this->goodsAttr->where('goods_gid',$gid)->where('typeAttr_taid',$v['taid'])->get();
		}
		View::with('spec',$spec);
		//货品列表数据
		$goodsListData = $this->db->where('goods_gid',$gid)->get();
		//将对应id转换成对应值
		foreach ($goodsListData as $k => $v) {
			$goodsListData[$k]['spec'] = $this->goodsAttr->where("gaid in (" . $v['combine'] . ")")->lists('gavalue');

		}
		View::with('goodsListData',$goodsListData);
		//一下是对货品添加时候不能重复添加的处理
		//货品总数
		$num = count($goodsListData);
		//可能的组合数量
		$possible = 1;
		foreach ($spec as $k => $v) {
			$possible *= count($v['select']);
		}
		//判断是否显示添加货品按钮，所有数据总数跟可能组合数座比较
		$is_show = $num<$possible ? 1 : 0;
		View::with('is_show',$is_show);
		View::make();
	}
	/**
	 * 编辑货品
	 */
	public function edit()
	{	//get参数，货品id，商品id，类型id
		$glid=Q('get.glid',0,'intaval');
		$gid=Q('get.gid',0,'intaval');
		$type_ID=Q('get.type_ID',0,'intaval');
		if(IS_POST)
		{	//执行模型中的编辑方法
			if(!$this->db->edit($glid))
			{	//编辑失败，提示乡音错误信息
				$this->error($this->db->getError());
			}
			//编辑成功，提示成功信心，跳转到首页
			View::success('修改成功',U('index',array('gid'=>$gid,'type_ID'=>$type_ID)));
		}
		//获取旧数据
		$oldData = $this->db->where("glid={$glid}")->first();
		View::with('oldData',$oldData)->make();
	}
	/**
	 * 删除货品
	 */
	public function del()
	{	//货品id
		$glid = Q('get.glid',0,'intaval');
		//执行删除，删除成功，跳转到首页
		if($this->db->where('glid',$glid)->delete())
		{
			View::success('删除成功');
		}
	}
	/**
	 * 异步检测货品是否存在
	 */
	public function ajaxCheck()
	{	//商品id，货品规格
		$gid=Q('post.gid');
		$spec=Q('post.spec');		
		$combine=implode(',',$spec);	
		//货品表中查询到，说明货品已存在
		if($this->db->where('goods_gid',$gid)->where('combine',$combine)->first())
		{
			View::ajax(0);
		}else
		{
			View::ajax(1);
		}
	}
}
